"""
测试方法流程：
    1. 实例化session对象
    2. session对象发请求
    3. 断言
    4. 关闭session

* 获取验证码： http://tpshop-test.itheima.net/index.php?m=Home&c=User&a=verify
* 登录： http://tpshop-test.itheima.net/index.php?m=Home&c=User&a=do_login
"""

import unittest
import requests


class TestTpshopLogin(unittest.TestCase):
    def test01_login_ok(self):
        # 验证码校验
        url_verify = 'http://tpshop-test.itheima.net/index.php?m=Home&c=User&a=verify'
        session = requests.Session()

        resp_verify = session.get(url_verify)
        self.assertIn('image', resp_verify.headers.get('Content-Type'))

        # 登录校验
        url_login = 'http://tpshop-test.itheima.net/index.php?m=Home&c=User&a=do_login'

        body_form = {
            'username': '13344445555',
            'password': '123456',
            'verify_code': '8888'
        }

        resp_login = session.post(url_login, data=body_form)
        resp_login_data = resp_login.json()
        # print(resp_login_data)
        self.assertEqual(200, resp_login.status_code)
        self.assertEqual(1, resp_login_data.get('status'))
        self.assertIn('成功', resp_login_data.get('msg'))

        # 关闭session
        session.close()

    def test02_user_err(self):
        # 验证码校验
        url_verify = 'http://tpshop-test.itheima.net/index.php?m=Home&c=User&a=verify'
        session = requests.Session()

        resp_verify = session.get(url_verify)
        self.assertIn('image', resp_verify.headers.get('Content-Type'))

        # 登录校验
        url_login = 'http://tpshop-test.itheima.net/index.php?m=Home&c=User&a=do_login'

        body_form = {
            'username': '13344448888',
            'password': '123456',
            'verify_code': '8888'
        }

        resp_login = session.post(url_login, data=body_form)
        resp_login_data = resp_login.json()
        print(resp_login_data)
        self.assertEqual(200, resp_login.status_code)
        self.assertEqual(-1, resp_login_data.get('status'))
        self.assertIn('不存在', resp_login_data.get('msg'))

        # 关闭session
        session.close()

    def test03_pwd_err(self):
        # 验证码校验
        url_verify = 'http://tpshop-test.itheima.net/index.php?m=Home&c=User&a=verify'
        session = requests.Session()

        resp_verify = session.get(url_verify)
        self.assertIn('image', resp_verify.headers.get('Content-Type'))

        # 登录校验
        url_login = 'http://tpshop-test.itheima.net/index.php?m=Home&c=User&a=do_login'

        body_form = {
            'username': '13344445555',
            'password': '1234561',
            'verify_code': '8888'
        }

        resp_login = session.post(url_login, data=body_form)
        resp_login_data = resp_login.json()
        # print(resp_login_data)
        self.assertEqual(200, resp_login.status_code)
        self.assertEqual(-2, resp_login_data.get('status'))
        self.assertIn('错误', resp_login_data.get('msg'))

        # 关闭session
        session.close()